/**
 * Rxjs Note.
 * 1. Observable 是数据的生成端，用 next(data) 推数据，用 subscript(observer) 注册数据处理函数。
    const foo = new Observable(subscriber => {
    subscriber.next(42);
    });

    foo.subscribe(x => {
    console.log(x);
    });
 * 模式：用 fecth api 产生数据，在 useEffect()中注册 setState()
 *   
 * 2. 关于 BehaviorSubject 见 https://stackoverflow.com/a/40231605/15172980
 * 
 * 3. 注册登录逻辑教程：https://jasonwatmore.com/post/2019/02/01/react-role-based-authorization-tutorial-with-example
 */

import axios from "@/tools/axios-config";
import { BehaviorSubject } from 'rxjs';

const currentUser = typeof localStorage !== 'undefined' ? localStorage.getItem('currentUser') : null;
const currentUserSubject = new BehaviorSubject(JSON.parse(currentUser));

function login(username, password) {

    axios.post('/login/', {
        username,
        password
    }).then((res) => {
        const currentUser = res.data;
        localStorage.setItem('currentUser', JSON.stringify(currentUser));
        currentUserSubject.next(currentUser);
        return currentUser;
    });
}

function logout() {
    axios.get('/logout', {
        headers: {
            'Authorization': `token ${auth.currentUser && auth.currentUser.token}`
        }
    }).then((data) => {
        localStorage.removeItem('currentUser');
        currentUserSubject.next(null);
    });
}


export const auth = {
    login,
    logout,
    currentUserObservable: currentUserSubject.asObservable(),
    get currentUser() { return currentUserSubject.value }
}

